const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");//将所有 Vue 组件中的所有已处理的 CSS 提取为单个 CSS 文件
module.exports = env => {
  if (!env) { env={} }
  let plugins = [
    new CleanWebpackPlugin(['dist']),
    new HtmlWebpackPlugin({template:'./app/views/index.html'})
  ];
  if (env.production) 
  {
    plugins.push(
      //修改全局变量 特别注意 "production" 要用双引号,否则无法报错
      new webpack.DefinePlugin({'process.env':{NODE_ENV:'"production"'}}),
      new ExtractTextPlugin("style.css")
    );
  }
  return {
    mode: env.production?'production':'development',
    entry: [
      './app/js/viewport.js',
      './app/js/main.js'
    ],
    output: {
      filename: '[name].min.js',
      path: path.resolve(__dirname, 'dist')
    },
    resolve: {
      extensions: ['.js', '.vue', '.json'],
      alias: {
        'vue$': 'vue/dist/vue.esm.js'
      }
    },
    module: {
      rules: [
        {
          test: /\.(jsx|js)$/,
          loader: 'babel-loader',
          exclude: /node_modules/
        },
        {
          test: /\.html$/,
          loader: 'html-loader'
        },
        {
          test: /\.vue$/,
          loader: 'vue-loader',
          options: {
            // css 局域化
            cssModules: {
              localIdentName: '[path][name]---[local]---[hash:base64:5]',
              camelCase: true
            },
            // px转rem
            loaders: env.production?{
              // css 单文件处理 + px2rem
              css: ExtractTextPlugin.extract({
                use: 'css-loader?minimize!px2rem-loader?remUnit=46.875&remPrecision=8',
                fallback: 'vue-style-loader' // <- 这是vue-loader的依赖，所以如果使用npm3，则不需要显式安装
              }),
              // scss 单文件处理 + px2rem
              scss: ExtractTextPlugin.extract({
                use: 'css-loader?minimize!px2rem-loader?remUnit=46.875&remPrecision=8!sass-loader',
                fallback: 'vue-style-loader'
              })
            }:{
              css:'vue-style-loader!css-loader!px2rem-loader?remUnit=46.875&remPrecision=8',
              scss:'vue-style-loader!css-loader!px2rem-loader?remUnit=46.875&remPrecision=8!sass-loader'
            }
          }
        },
        {
          test: /\.scss$/,
          loader: ["style-loader", "css-loader", "sass-loader"]
        },
      ]
    },
    plugins,
    devServer: {
      contentBase: path.join(__dirname, "dist"),//静态文件的输出路径
      compress: true,//整个服务开启gzip压缩
      port: 9000//端口号
    }
  }
}
